﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Web.Mvc;

namespace MvcServiceLibrary
{
    public abstract class SerializedView : IView
    {
        public abstract string ContentType { get; }
        public abstract string GetContent(object viewData);

        public void RenderView(ViewContext viewContext)
        {
            viewContext.HttpContext.Response.ContentType = ContentType;
            object viewData = viewContext.ViewData;

            if (viewData is Exception)
            {
                Exception exc = ((Exception)viewData).InnerException;
                if (exc is HttpException)
                {
                    viewContext.HttpContext.Response.StatusCode = ((HttpException)exc).GetHttpCode();
                }
                else
                {
                    viewContext.HttpContext.Response.StatusCode = 500;
                }
                viewContext.HttpContext.Response.StatusDescription = exc.Message;

                viewData = new SimpleException(exc);
            }

            if (viewContext.ViewData != null)
            {
                try
                {
                    viewContext.HttpContext.Response.Write(GetContent(viewData));
                }
                catch (System.Runtime.Serialization.SerializationException serializationEx)
                {
                    viewContext.HttpContext.Response.StatusCode = 500;
                    viewContext.HttpContext.Response.StatusDescription = serializationEx.Message;
                }
            }
        }
    }
}
